package com.sss.springcloud.degrade;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.sss.springcloud.common.Result;
import com.sss.springcloud.entities.Payment;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

/**
 * 降级自定义服务消息返回
 * @author sss
 * @date 2020-03-12 11:51
 **/
@RestController
public class FallbackController {

    @Value("${server.port}")
    private String serverPort;

    /**
     * 只配置blockHandler时，代表降级后调用的方法是fallbackHandler
     * fallbackHandler方法的参数必须跟当前方法的参数一致并且要加上BlockException这个参数
    **/
    @GetMapping("/fallback/payment/get/one/{id}")
    @SentinelResource(value = "fallback",blockHandler = "fallbackHandler")
    public Result fallback(@PathVariable("id")Integer id){
        if (id==5) {
            throw new IllegalArgumentException("参数不合法异常！！！！\t"+serverPort);
        }else if (id==6){
            throw new RuntimeException("运行时异常！！！\t"+serverPort);
        }
        Payment payment = new Payment(211L, "fallbackTest\t"+serverPort);
        return Result.succes(payment);
    }

    public Result fallbackHandler(Integer id, BlockException ex){
        return Result.fail(444,"fallback兜底方法");
    }


    /**
     * 配置了CustomFallbackHandler和blockHandler时，代表降级后调用的方法是CustomFallbackHandler这个类里面的fallbackHandler2方法
     * CustomFallbackHandler类中方法的参数必须跟当前方法的参数一致并且要加上BlockException这个参数
     **/
    @GetMapping("/fallback/payment/get/two/{id}")
    @SentinelResource(value = "fallback2", blockHandlerClass = CustomFallbackHandler.class,blockHandler = "fallbackHandler2")
    public Result fallback2(@PathVariable("id")Integer id){
        if (id==5) {
            throw new IllegalArgumentException("参数不合法异常！！！！\t"+serverPort);
        }else if (id==6){
            throw new RuntimeException("运行时异常！！！\t"+serverPort);
        }
        Payment payment = new Payment(211L, "fallbackTest\t"+serverPort);
        return Result.succes(payment);
    }

    @GetMapping("/fallback/payment/get/three/{id}")
    @SentinelResource(value = "fallback3", fallback ="fallbackException")
    public Result fallback3(@PathVariable("id")Integer id){
        if (id==5) {
            throw new IllegalArgumentException("参数不合法异常！！！！\t"+serverPort);
        }else if (id==6){
            throw new RuntimeException("运行时异常！！！\t"+serverPort);
        }
        Payment payment = new Payment(211L, "fallbackTest\t"+serverPort);
        return Result.succes(payment);
    }
    public  Result fallbackException(Integer id, Throwable ex){

        return Result.fail(444,"服务内部繁忙，请稍后再试(T_T)！！！");
    }
}
